package com.jdd.modules.mqtt.server.revice;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jdd.common.util.SnowFlakeUtil;
import com.jdd.dao.entity.TDeviceCmdRequest;
import com.jdd.dao.service.TDeviceCmdRequestService;
import com.jdd.modules.deviceLog.service.ITUserCmdLogService;
import com.jdd.modules.mqtt.constant.MqttCmdConstant;
import com.jdd.modules.userOptionLog.service.ITUserOptionLogService;
import com.jdd.modules.userstaff.entity.TUserDevice;
import com.jdd.modules.userstaff.service.ITUserDeviceService;
import com.jdd.modules.userstaff.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @program: jdd-people-passage
 * @ClassName ReciveMqttQrResponseService
 * @description: 设备回复执行结果topic消息处理类
 * @author: zsj
 * @create: 2022-03-24 09:56
 * @Version 1.0
 **/
@Slf4j
@Service("mqttFaceSnResponseStrategy")
public class ReciveMqttFaceSnResponseServiceStrategy implements IReciveMqttBaseStrategy {
    @Autowired
    private TDeviceCmdRequestService cmdRequestService;


    @Autowired
    private IUserService userService;
    @Resource
    private ITUserDeviceService userDeviceService;
    @Resource
    private ITUserCmdLogService userCmdLogService;
    @Resource
    private ITUserOptionLogService userOptionLogService;

    /**
     * 处理从mqtt接收到的设备执行命令结果回复消息接口
     * 所有指令都需要储存响应表以及更新请求表
     * 人脸创建指令回复处理流程：
     * 1.成功则更新t_user_device的用户id和sn对的上的记录状态为启用
     * 2.不成功则不更新状态
     * <p>
     * 人脸删除指令回复处理流程
     * 1.成功则删除对应用户id和sn的记录，不成功则不动
     * <p>
     * <p>
     * // TODO: 2022/10/13 暂时只有新增和删除，修改再做
     *
     * @param message 消息
     * @return void
     * @Description
     * @Author zsj
     * @Date 2022-03-24 9:53
     **/
    @Override
    public void handleMessage(String message) {
        log.info("接收到mqtt设备回复执行结果，消息：{}", message);
        JSONObject jsonObject = JSONObject.parseObject(message);
        String responseCmd = jsonObject.getString("cmd");
        String cmdId = jsonObject.getString("cmd_id");
        Integer code = jsonObject.getInteger("code");
        LambdaQueryWrapper<TDeviceCmdRequest> requestLambdaQueryWrapper = new LambdaQueryWrapper<>();
        requestLambdaQueryWrapper.eq(TDeviceCmdRequest::getCmdId, cmdId);
        TDeviceCmdRequest cmdRequest = cmdRequestService.getOne(requestLambdaQueryWrapper);
        if (cmdRequest != null) {
            JSONObject requstCmdJson = JSONObject.parseObject(cmdRequest.getCmd());
            String clientId = requstCmdJson.getString("client_id");
            if (responseCmd.equals(MqttCmdConstant.PeopleController.Create.CREATE_FACE) || responseCmd.equals(MqttCmdConstant.PeopleController.Create.UPDETE_FACE_EX)) {
                String perId = requstCmdJson.getString("per_id");
                if (code == 0) {
                    TUserDevice tUserDevice = new TUserDevice();
                    tUserDevice.setId(SnowFlakeUtil.getId());
                    tUserDevice.setUserId(perId);
                    tUserDevice.setDeviceId(clientId);
                    tUserDevice.setUserCardId(requstCmdJson.getString("idcardper"));
                    tUserDevice.setCrossForever(1);
                    userDeviceService.save(tUserDevice);
                    log.info("创建用户" + perId + "人脸成功,设备id为" + clientId);
                }
            } else if (responseCmd.equals(MqttCmdConstant.DoorController.OPEN_DOOR)) {

            } else if (responseCmd.equals(MqttCmdConstant.PeopleController.Delete.DELETE_FACE)) {
                String per_id = requstCmdJson.getString("per_id");
                if (code==405){
                    LambdaQueryWrapper<TUserDevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(TUserDevice::getUserId, per_id);
                    lambdaQueryWrapper.eq(TUserDevice::getDeviceId, clientId);
                    userDeviceService.remove(lambdaQueryWrapper);
                    log.info("设备回应为405.删除用户{}设备{}关联信息",per_id,clientId);
                }
                if (code == 0) {
                    LambdaQueryWrapper<TUserDevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(TUserDevice::getUserId, per_id);
                    lambdaQueryWrapper.eq(TUserDevice::getDeviceId, clientId);
                    userDeviceService.remove(lambdaQueryWrapper);
                    if (cmdRequest.getRequestType() != 6) {
                        List<String> bindedDevice = userService.getBindedDevice(per_id);
                        if (CollectionUtils.isEmpty(bindedDevice)){
                            userService.removeById(per_id);
                        }
                    }
                    log.info("删除用户" + per_id + "人脸成功,设备id为" + clientId);
                }

            }
        } else {
            log.info("非平台系统发送指令");
        }
    }
}
